package com.spirng.leetcode.day02;

public class MyLinkedList {
    public static void main(String[] args) {
        MyLinkedList myLinkedList = new MyLinkedList();
        myLinkedList.addAtHead(1);
        myLinkedList.addAtTail(3);
        myLinkedList.addAtIndex(1, 2);    // 链表变为 1->2->3
        int i = myLinkedList.get(1);// 返回 2
        myLinkedList.deleteAtIndex(1);    // 现在，链表变为 1->3
        int i1 = myLinkedList.get(1);
    }
    int size;
    ListNode1 head,tail;

    public MyLinkedList() {
        size=0;
        head=new ListNode1(0);
        tail=new ListNode1(0);
        head.next=tail;
        tail.prev=head;
    }
    public int get(int index){
        if(index<0||index>=size){
            return -1;
        }
        ListNode1 prev=head;
        for (int i = 0; i <=index; i++) {
            prev=prev.next;
        }
        return prev.val;
    }
    public void addAtHead(int val){
     addAtIndex(0,val);
    }
    public void addAtTail(int val){
     addAtIndex(size,val);
    }
    public void addAtIndex(int index,int val){
        if(index>size){
            return;
        }
        if(index<0){
            index=0;
        }
        size++;
        ListNode1 prev=head;
        for (int i = 0; i < index; i++) {
            prev=prev.next;
        }
        ListNode1 listNode1 = new ListNode1(val);
        listNode1.next=prev.next;
        prev.next.prev=listNode1;
        prev.next=listNode1;
        listNode1.prev=prev;
    }
    public void  deleteAtIndex(int index){
        if(index<0||index>=size){
            return;
        }
        size--;
        ListNode1 node1=head;
        for (int i = 0; i < index; i++) {
            node1=node1.next;
        }
        node1.next.next.prev=node1;
        node1.next=node1.next.next;
    }


}
class ListNode1{
    int val;
    ListNode1 next,prev;

    public ListNode1() {
    }
    public  ListNode1(int val){
        this.val=val;
    }
}